<?php
/**
 * Created by PhpStorm.
 * User: 68008000
 * Date: 2017/12/5
 * Time: 14:31
 */

namespace app\common\model;


use houdunwang\arr\Arr;
use think\Model;

class Rule extends Model
{
    protected $table = 'shop_auth_rule';
    protected $pk = 'id';
    //添加
    public function add($data){
        //1添加文章数据库
        $result = $this->validate(true)->save($data);
        if(false === $result){
            // 验证失败 输出错误信息
            return ['valid'=>0,'msg'=>$this->getError()];
        }else{
            return ['valid'=>1,'msg'=>'添加成功'];
        }
    }
    /**
     * 获取除去自己和自己子集的数据
     */
    //1.
    public function getFieldData($id)
    {
        $ids = $this->getSon(db('auth_rule')->select(), $id);
        $ids[] = $id;
        $data = db('auth_rule')->whereNotIn('id', $ids)->select();
        return Arr::tree($data, 'title', 'id', 'pid');
    }

    //2.获得子集
    public function getSon($data, $id)
    {
        static $temp = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $id) {
                $temp[] = $v['id'];
                $this->getSon($data, $v['id']);
            }
        }
        return $temp;
    }

    //编辑
    public function edit($data)
    {
        $id = input('param.id');
        $result = $this->validate(true)->save($data, ['id' => $id]);
        if (false === $result) {
            return ['valid' => 0, 'msg' => $this->getError()];
        } else {
            return ['valid' => 1, 'msg' => '编辑成功'];
        }
    }
    //删除
    public function del($id){
        $check = db('auth_rule')->where('pid', $id)->select();
        if ($check) {
            return $this->error('请先删除子集数据');
        }
        $res = Rule::destroy($id);
        if ($res){
            return ['valid'=>1,'msg'=>'删除成功'];
        }else{
            return ['valid'=>0,'msg'=>'删除失败'];
        }

    }

}